/*
 * Copyright (c) Family. All Rights Reserved
 */

package com.driving.exam.spider;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import com.driving.exam.entity.Exercise;
import com.driving.exam.service.IDrivingExamService;
import com.driving.exam.spider.parser.DrivingExamParser;

/**
 * 下载题库任务
 *
 * @author SAGITTAR
 */
@Component(value = "drivingExamSpider")
public class DrivingExamSpider {

    private static final Logger LOGGER = LogManager.getLogger(DrivingExamSpider.class);

    private static final String BASE_DIRECTORY = "E:/driving/exercise/";

    private static final List<String> FILE_LIST;

    static {
        FILE_LIST = new ArrayList<>(5);
        FILE_LIST.add("subject1/A1-A3-B1.txt");
        FILE_LIST.add("subject1/A2-B2.txt");
        FILE_LIST.add("subject1/C1-C2.txt");
        FILE_LIST.add("subject4/A1-A2-A3-B1-B2.txt");
        FILE_LIST.add("subject4/C1-C2.txt");
    }

    private final IDrivingExamService drivingExamService;

    private final DrivingExamParser drivingExamParser;

    public DrivingExamSpider(IDrivingExamService drivingExamService, DrivingExamParser drivingExamParser) {
        this.drivingExamService = drivingExamService;
        this.drivingExamParser = drivingExamParser;
    }

    public void execute() throws Exception {
        for (String file : FILE_LIST) {
            List<Exercise> exerciseList = new ArrayList<>();
            File fileDirectory = Paths.get(BASE_DIRECTORY, file).toFile();
            try (RandomAccessFile randomAccessFile = new RandomAccessFile(fileDirectory, "r")) {
                String line;
                while (StringUtils.isNotBlank((line = randomAccessFile.readLine()))) {
                    line = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    if (StringUtils.isNotBlank(line)) {
                        LOGGER.warn(line);
                        // 0为编号；1为章节；2为题目；3-6为选项（如果有），7为答案，8为图片（如果有），9未知，10为解析，11-12未知
                        String[] info = line.split(",");
                        Exercise exercise = new Exercise();
                        exercise.setSubjectId(Integer.parseInt(StringUtils.substringBetween(file, "subject", "/")));
                        exercise.setType(StringUtils.substringBetween(file, "/", "."));
                        exercise.setChapter(Integer.parseInt(trimQuotation(info[1])));
                        exercise.setTitle(trimQuotation(info[2]));
                        List<String> choiceList = new ArrayList<>(4);
                        choiceList.add(trimQuotation(info[3]));
                        choiceList.add(trimQuotation(info[4]));
                        if (StringUtils.isNotBlank(trimQuotation(info[5]))) {
                            choiceList.add(trimQuotation(info[5]));
                        }
                        if (StringUtils.isNotBlank(trimQuotation(info[6]))) {
                            choiceList.add(trimQuotation(info[6]));
                        }
                        exercise.setChoiceList(choiceList);
                        exercise.setAnswer(Integer.parseInt(trimQuotation(info[7])));
                        if (StringUtils.isNotBlank(trimQuotation(info[8]))) {
                            exercise.setPicture(trimQuotation(info[8]));
                        }
                        exercise.setExplanation(trimQuotation(info[10]));
                        exercise.setOrdinal(Integer.parseInt(trimQuotation(info[0]).trim()));
                        exerciseList.add(exercise);
                    }
                }
            }
            int everyTime = 30;
            int times = 0;
            while (times * everyTime < exerciseList.size()) {
                int start = times++ * everyTime;
                if (start > exerciseList.size()) {
                    break;
                }
                int end = start + everyTime;
                if (end > exerciseList.size()) {
                    end = exerciseList.size();
                }
                drivingExamService.saveBatch(drivingExamParser.parse(exerciseList.subList(start, end)), end - start);
                TimeUnit.SECONDS.sleep(3);
            }
            TimeUnit.SECONDS.sleep(5);
        }
    }

    /**
     * 去除两端引号
     *
     * @return 去除两端引号
     */
    private static String trimQuotation(String info) {
        return StringUtils.remove(info, "\"");
    }
}
